#include <iostream>
#include <string>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <string>
#include <unistd.h>

void Usage(const char *proc)
{
    std::cout << proc << " serverop serport" << std::endl;
    exit(1);
}

// 服务端的ip 和port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
    }

    int svrport = std::stoi(argv[2]);
    std::string svrip = argv[1];

    // 创建通信的套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cout << "创建套接字失败" << std::endl;
        exit(-1);
    }
    // 不需要绑定，在发送的时候，由OS自动连接

    // 服务器的信息
    struct sockaddr_in server;
    bzero(&server, sizeof(server));
    server.sin_addr.s_addr = inet_addr(svrip.c_str());
    server.sin_family = AF_INET;
    server.sin_port = htons(svrport);

    // 可以进行通信了
    while (true)
    {
        std::string buffer;
        std::cout << "please Enter#";
        std::getline(std::cin, buffer);

        // 直接发
        ssize_t n = sendto(sockfd, buffer.c_str(), buffer.size(), 0, (struct sockaddr *)&server, sizeof(server));

        if (n > 0)
        {
            // 发送成功,接下来就是收消息
            char outbuffer[1024];
            struct sockaddr_in tmp;
            socklen_t len;
            ssize_t m = recvfrom(sockfd, outbuffer, sizeof(outbuffer) - 1, 0, (struct sockaddr *)&tmp, &len);
            if (m > 0)
            {
                outbuffer[m] = 0;
                std::cout << "server echo#" << outbuffer << std::endl;
            }
            else
            {
                break;
            }
        }
        else
        {
            break;
        }
    }
    close(sockfd);
    return 0;
}
